import time

import uvicorn
from fastapi import FastAPI, BackgroundTasks
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html, get_swagger_ui_oauth2_redirect_html
from starlette.staticfiles import StaticFiles


# 定义标签
tags_metadata = [
    {
        "name": "用户管理",
        "description": "用户管理相关接口",
        "externalDocs": {
            "description": "更多信息",
            "url": "https://xiaoxie.com",
        },
    },
    {
        "name": "订单管理",
        "description": "订单管理相关接口",
        "externalDocs": {
            "description": "更多信息",
            "url": "https://xiaoxie.com",
        },
    }
]


# 创建 FastAPI 应用实例，并把默认的/docs请求禁用，把默认的/redoc请求禁用
# debug表示是否开启调试模式，默认是False
app = FastAPI(docs_url=None,redoc_url= None,debug=True,
              title="超级工厂项目" ,                        # 项目标题
              description="这里是关于项目的简短描述",        # 项目描述
              version="1.0.1",                            # 项目版本
              terms_of_service= "http://xiaoxie.com",     # 服务条款
              contact={                                   # 联系人信息
                  "name": "小谢",
                  "url": "http://xiaoxie.com",
                  "email": "xiaoxie@xiaoxie.com",
              },
              license_info={                               # 协议信息
                  "name": "Apache 2.0",
                  "url": "https://github.com/xiaoxie/python_learning_path/blob/main/LICENSE",
              },
              openapi_tags=tags_metadata,                   # 传入给定标签元数据数组
              openapi_url="/docs/v1/docs.json"              # 指定 OpenAPI 文档的 URL
              )

app.mount("/static", StaticFiles(directory="../static"), name="static")    # 静态文件

@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/docs/v1/docs.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()

@app.get("/redoc", include_in_schema=False)
def custom_redoc():
    return get_redoc_html(
        openapi_url = "/docs/v1/docs.json",
        title = "Redoc for FastAPI",
        redoc_js_url="/static/redoc.standalone.js"
    )

# 这里的tags可以有多个，所以一个api可以属于多个分类中
@app.get("/users",tags=["用户管理"])
async def get_users():
    return [
        {
            "id": 1,
            "username": "张三",
            "description": "张三的描述"
        },
        {
            "id": 2,
            "username": "李四",
            "description": "李四的描述"
        }
    ]

if __name__ == '__main__':

    uvicorn.run("main:app", host="127.0.0.1", port=8014, reload=True)